package info.liuxing.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * IoUtil
 *
 * @author liuxing (SE)
 * @summary IoUtil
 * @Copyright (c) 2017, Lianjia Group All Rights Reserved.
 * @since 2017-12-04 00:32
 */
public class IOUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(IOUtil.class);

    private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;

    /**
     * 写入文件
     *
     * @param is
     * @param toFile
     */
    public static void writeTo(final InputStream is, final String toFile) {
//        FileOutputStream fos = null;
//
//        try {
//            fos = new FileOutputStream(new File(toFile));
//
//            int len;
//            byte[] buf = new byte[DEFAULT_BUFFER_SIZE];
//            while ((len = is.read(buf)) != -1) {
//                fos.write(buf, 0, len);
//            }
//            fos.flush();
//        } catch (IOException e) {
//            LOGGER.error(e.getMessage(), e);
//        } finally {
//            if (Objects.nonNull(fos)) {
//                try {
//                    fos.close();
//                } catch (IOException e) {
//                    LOGGER.error(e.getMessage(), e);
//                }
//            }
//
//            if (Objects.nonNull(is)) {
//                try {
//                    is.close();
//                } catch (IOException e) {
//                    LOGGER.error(e.getMessage(), e);
//                }
//            }
//        }

        try {
            int byteCount = FileCopyUtils.copy(is, new FileOutputStream(new File(toFile)));
            LOGGER.debug("文件大小:{}字节", byteCount);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

}
